package com.heima.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;
import java.util.List;

@Configuration
public class KafkaStreamHelloListener {
    @Bean
    public KStream<String,String> kStream(StreamsBuilder builderBuder) {
        //创建kstream对象，同时指定从那个topic中接收消息
        KStream<String,String> stream = builderBuder.stream("itcast-topic-input");
        //处理消息的value
        stream.flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    @Override
                    public Iterable<String> apply(String value) {
                        List<String> list = Arrays.asList(value.split(" "));
                        System.out.println(list);
                        return list;
                    }
                })      //按照value进行聚合处理
                .groupBy((key,value)->value)
                //时间窗口
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                //统计单词个数
                .count()
                //转换为kstream
                .toStream()
                .map((key,value)->{
                    System.out.println(key+":"+value);
                    return new KeyValue<>(key.key().toString(),value.toString());
                }).to("itcast-topic-output");
    return stream;
    }
}
